<template>
	<view class="router-view uni-animation-fade" v-if="info">
		<!-- 顶部信息 -->
		<view class="info container border border-bottom" style="padding-bottom: 0;">
			<!-- 基本信息 -->
			<view class="border border-bottom pb-10">
				<!-- 标题 -->
				<view class="title fz-15 bold">{{ info.title }}</view>

				<!-- 标签列表 -->
				<!-- <view class="tag-list mt-5">
          <view class="uni-tag">{{ info.type_name }}</view>
          <view class="uni-tag" v-if="info.commission > 0"
            >推广{{ info.commission }}元</view
          >
          <view class="uni-tag">急</view>
        </view> -->

				<!-- 赏金 -->
				<view class="box box-column-center box-between mt-10">
					<view>
						<!-- <text class="cl-basic mr-5">已托管赏金</text> -->
						<text class="cl-main fz-24 bold">￥{{ info.bounty || 0 }}</text>
					</view>

					<view class="bold" @tap="toFilesPage" v-if="info.attachment.length">
						<text class="icon icon-annex"></text>
						<text style="font-size: 20rpx;">剩余 &nbsp;&nbsp;&nbsp;<span style="font-size: 20rpx;color: red;margin-left: 10rpx;">{{ info.time_desc }}</span></text>
					</view>
				</view>
			</view>

			<!-- 其他信息 -->
			<view class="box box-between box-column-center fz-12 cl-second pt-10 pb-10">
				<view class="user-info box box-column-center">
					<view class="uni-avatar uni-avatar-sm mr-5">
						<image src="/static/images/menu_1.png" />
					</view>
					<view>{{ info.name }}</view>
				</view>

				<view style="text-align: center;">{{ info.view_count || 0 }}人浏览/{{
            info.delivery_count || 0
          }}人投标</view>

				<view style="color: red;">推广佣金 {{info.commission}}</view>

			</view>
		</view>

		<!-- 阶段 -->


		<!-- Tab展示 -->
		<uni-tab :tab-title="tabTitle" :has-active-border="true" @change="onTabChange">
			<!-- 详细信息 -->
			<view class="container" style="overflow: auto;" slot="content" v-html="info.desc || '空空如也~'" v-show="currentIndex == 0">
			</view>

			<!-- 投标记录 -->
			<view class="container" slot="content" v-show="currentIndex == 1">
				<view class="work-list" v-if="info.work_list && info.work_list.length">
					<view class="item mb-10" v-for="(item, index) in info.work_list" :key="index">
						<work-item :item="item" :currentProgress="currentProgress" :role="info.role" :isBounty="info.bounty_status == 1"></work-item>
					</view>
				</view>
				<!-- 无数据 -->
				<uni-load-more :status="5" v-else></uni-load-more>
			</view>

			<!-- 修改记录 -->
			<view class="container" slot="content" v-show="currentIndex == 2">
				<view class="update-list" v-if="updates.length">
					<view class="item mb-10" v-for="(item, index) in updates" :key="index">
						<update-item :item="item" :role="info.role"></update-item>
					</view>

					<view class="text-center mt-40">
						<navigator :url="`/pages/index/modify?type=1&taskId=${this.info.id}&role=employer`"
						 v-if="info.role == 'employer' && info.status <= 7"><button class="uni-button uni-button-main">
								我要创建修改
							</button>
						</navigator>
					</view>
				</view>

				<!-- 无数据 -->
				<view class="text-center" v-else>
					<uni-load-more :status="5">
						<view slot="extra">暂无任何修改记录</view>
					</uni-load-more>

					<navigator :url="`/pages/index/modify?type=1&taskId=${info.id}&role=employer`" v-if="info.role == 'employer' && info.status <= 7">
						<button class="uni-button uni-button-main">我要创建修改</button>
					</navigator>
				</view>
			</view>

			<!-- 交付稿件 -->
			<view class="container" slot="content" v-show="currentIndex == 3">
				<view class="work-list" v-if="deliverys.length">
					<view class="item mb-10" v-for="(item, index) in deliverys" :key="index">
						<work-item :item="item" :currentProgress="currentProgress" :role="info.role" :isBounty="info.bounty_status == 1"></work-item>
					</view>
				</view>

				<!-- 无数据 -->
				<uni-load-more :status="5" v-else></uni-load-more>
			</view>
		</uni-tab>

		<!-- 右下角 -->
		<view class="fixed-bottom-right">
			<view class="text-center pointer" @click="focusTask">
				<view class="icon icon-like fz-30" :class="info.focused == 1 ? 'cl-main' : 'cl-second'"></view>
				<view>关注</view>
			</view>
			<view class="text-center pointer" @click="toChatPage(info.uid)" v-if="info.role != 'employer'">
				<view class="icon icon-message-fill cl-main fz-30"></view>
				<view>沟通</view>
			</view>
			<button class="uni-button uni-button-clear text-center pointer" open-type="share" @click="onShare">
				<view class="icon icon-share cl-main fz-30"></view>
				<view>分享</view>
			</button>
		</view>

		<!-- 底部栏 -->
		<view class="uni-footer box box-center text-center bcl-white border border-top" v-if="buttonStatus != 0">
			<view class="box-1 bcl-main-new cl-white text-center pointer pointer-filter" :class="{ 'bcl-disabled': buttonDisabled }"
			 @tap="onButtonClick">{{ buttonText }}</view>
		</view>

		<!-- 威课确认付款方式模态框 -->
		<uni-dialog v-model="dealShow" cancelBtnText="拒绝" :sync="true" @cancel="savePayType(2)" @submit="savePayType(1)">
			<view class="container text-center" slot="content">
				<text>确定同意当前付款方式吗?</text>
			</view>
		</uni-dialog>

		<!-- 雇主验收模态框 -->
		<uni-dialog v-model="checkShow" cancelBtnText="失败" confirmBtnText="通过" :sync="true" @cancel="checkTask(2)" @submit="checkTask(1)">
			<view class="container text-center" slot="content">
				<text>确定验收通过吗?</text>
			</view>
		</uni-dialog>

		<!-- 发布按钮 -->
		<!-- <div
      class="send-btn pointer"
      @click="toSendPage"
    >
      <image
        src="/static/images/release_1.png"
        style="width: 50px; height: 50px;"
      ></image>
    </div> -->
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import uniDialog from "@/components/dialog";
	import uniTab from "@/components/tab";
	import uniProgressBar from "@/components/progressBar";
	import uniLoadMore from "@/components/loadMore";
	import workItem from "./components/workItem";
	import updateItem from "./components/updateItem";

	import {
		detailTask,
		listUpdateInfo,
		listDelivery,
		postPayType,
		dealPayType,
		checkTask,
		focus,
		cancelFocus,
	} from "@/apis/task";

	// #ifdef APP-PLUS
	import appShare, {
		closeShare
	} from "@/utils/share";
	// #endif

	export default {
		data() {
			return {
				id: "",
				info: null,
				updates: [],
				deliverys: [],
				progressData: [],

				currentIndex: 0,
				currentProgress: -1,

				dealShow: false,
				checkShow: false,
				attachment: []
			};
		},

		onLoad(options) {
			this.id = options.id;
			this.detailTask();
		},

		onShow() {
			this.detailTask();
		},

		// 微信小程序分享
		onShareAppMessage() {
			return {
				title: this.info.title,
				path: `/task/detail?id=${this.info.id}`,
			};
		},

		methods: {


			toSendPage() {

				let url = uni.getStorageSync("userInfo")
				if (url) {
					uni.navigateTo({
						url: '/pages/index/release/submit?type=1'
					});

				} else {

					uni.navigateTo({
						url: '/user/login'
					});
				}
			},
			/*
			 * 获取任务详情
			 */
			async detailTask() {
				let params = {
					id: this.id,
				};

				let {
					code,
					data
				} = await detailTask(params);
				console.log(data);
				if (code == 200) {
					data.focused = data.focused == 0 ? false : true;
					this.info = data;
					this.initProgressData();
					this.listUpdateInfo();
					this.listDelivery();
				}
			},

			/**
			 * 关注/取消关注
			 */
			async focusTask() {
				let params = {};

				if (this.info.focused) {
					params = {
						id: this.info.id,
					};
				} else {
					params = {
						task_id: this.info.id,
					};
				}

				let {
					code,
					data
				} = this.info.focused ?
					await cancelFocus(params) :
					await focus(params);

				if (code == 200) this.info.focused = !this.info.focused;
			},

			/*
			 * 获取修改记录列表
			 */
			async listUpdateInfo() {
				let params = {
					id: this.id,
				};

				let {
					code,
					data
				} = await listUpdateInfo(params);

				if (code == 200) {
					let list = [];

					for (let key in data) {
						list.push(data[key]);
					}

					list.forEach((item) => {
						item.files = item.files.filter((file) => file);

						item.files.forEach((file) => {
							file.url = `https://zhihuawang.oss-cn-beijing.aliyuncs.com/${file.url}`;
						});

						item.fh &&
							item.fh.forEach((citem) => {
								citem.files = citem.files.filter((file) => file);

								citem.files.forEach((file) => {
									file.url = `https://zhihuawang.oss-cn-beijing.aliyuncs.com/${file.url}`;
								});

								citem.backToDesc = item.desc;
								list.push(citem);
							});
					});

					this.updates = list;
				}
			},

			/**
			 * 获取交付稿件列表
			 */
			async listDelivery() {
				let params = {
					id: this.info.id,
				};
				let resp = await listDelivery(params);
				console.log(resp);

				if (resp.code == 200) this.deliverys = resp.data || [];
			},

			/*
			 * 招标任务保存付款方式
			 */
			async savePayType(type = 1) {
				let isEmployee = this.info.role == "employee";

				let params = {
					task_id: this.info.id,
					pay_type: 1,
				};

				if (isEmployee) {
					delete params.pay_type;
					params.type = type;
				}

				let {
					code,
					data
				} = isEmployee
					?
					await dealPayType(params) :
					await postPayType(params);

				if (code == 200) {
					this.$toast("确认完毕~");
					this.dealShow = false;
					setTimeout(() => {
						this.detailTask();
					}, 1000);
				}
			},

			/*
			 * 验收
			 */
			async checkTask(status = 1) {
				let params = {
					work_id: this.worker.id,
					status,
				};

				let {
					code,
					data
				} = await checkTask(params);

				if (code == 200) {
					this.$toast("操作成功~");
					this.checkShow = false;
					setTimeout(() => {
						this.detailTask();
					}, 1000);
				}
			},

			/**
			 * 按钮点击
			 */
			onButtonClick() {
				// 游客
				if (this.info.role == "visitor") {
					uni.navigateTo({
						url: "/user/login",
					});
				} else if (this.info.role == "employee") {
					// 我要投标
					if (this.buttonStatus == 1) {
						console.log("-----> 投标信息：",this.info);
						uni.navigateTo({
							url: `/pages/index/modify?type=4&taskId=${this.info.id}&taskType=${this.info.task_type}`,
						});
					}

					// 确认付款方式（弹窗选择）
					if (this.buttonStatus == 6) this.dealShow = true;

					// 交付稿件
					if (this.buttonStatus == 7) {
						uni.navigateTo({
							url: `/pages/index/modify?type=3&taskId=${this.info.id}&taskType=${this.info.task_type}&taskSort=${this.info.delivery_sort}`,
						});
					}

					// 评价
					if (this.buttonStatus == 10) {
						uni.navigateTo({
							url: `/task/rate?taskId=${this.info.id}&role=${this.info.role}&workId=${this.worker.id}`,
						});
					}
				} else {
					// 托管赏金
					if (this.buttonStatus == 4) {
						uni.navigateTo({
							url: `/pay/pay?type=2&taskId=${this.info.id}&worker=${this.worker.nickname}&workerPrice=${this.worker.price}`,
						});
					}

					// 确认付款方式
					if (this.buttonStatus == 5) this.savePayType();

					// 验收（弹窗选择）
					if (this.buttonStatus == 7) this.checkShow = true;

					// 评价
					if (this.buttonStatus == 8) {
						uni.navigateTo({
							url: `/task/rate?taskId=${this.info.id}&role=${this.info.role}&workId=${this.worker.id}`,
						});
					}
				}
			},

			/*
			 * 初始化进度数据
			 */
			initProgressData() {
				let info = this.info;

				if (info.task_type == "xuanshang") {
					// 悬赏模式
					this.progressData = [{
							name: "发布需求，委托赏金",
						},
						{
							name: "威客投标",
						},
						{
							name: "雇主选稿",
						},
						{
							name: "中标公示",
						},
						{
							name: "验收付款",
						},
						{
							name: "评价",
						},
					];

					// 判断进度
					if (info.status >= 3) {
						this.currentProgress = 0;
						this.progressData[0].time = info.created_at.split(" ")[0];
					}
					if (info.status >= 4 && info.work_list.length) {
						this.currentProgress = 1;
						this.progressData[1].time = info.created_at.split(" ")[0];
					}
					if (info.status >= 5) {
						info.work_list.forEach((item) => {
							if (item.status == 1) {
								this.currentProgress = 2;
								this.progressData[2].time = info.selected_work_at.split(" ")[0];
							}
						});
					}
					if (info.status >= 6 && info.publicity_at) {
						this.currentProgress = 3;
						this.progressData[3].time = info.publicity_at.split(" ")[0];
					}
					if (info.status >= 7 && info.checked_at) {
						this.currentProgress = 4;
						this.progressData[4].time = info.checked_at.split(" ")[0];
					}
					if (info.status >= 9 && info.end_at) {
						this.currentProgress = 5;
						this.progressData[5].time = info.end_at.split(" ")[0];
					}
				} else {
					// 招标模式
					this.progressData = [{
							name: "发布需求",
						},
						{
							name: "服务商报价",
						},
						{
							name: "选择服务商并托管资金",
						},
						{
							name: "服务商工作",
						},
						{
							name: "验收付款",
						},
						{
							name: "评价",
						},
					];

					// 判断进度
					if (info.status >= 3) {
						this.currentProgress = 0;
						this.progressData[0].time = info.created_at.split(" ")[0];
					}
					if (info.status >= 4 && info.work_list.length) {
						this.currentProgress = 1;
						this.progressData[1].time = info.created_at.split(" ")[0];
					}
					if (info.status >= 5) {
						info.work_list.forEach((item) => {
							if (item.status == 1) {
								this.currentProgress = 2;
								this.progressData[2].time = info.selected_work_at.split(" ")[0];
							}
						});
					}
					if (info.status >= 6 && info.checked_at) {
						this.currentProgress = 3;
						this.progressData[3].time = info.checked_at.split(" ")[0];
					}
					if (info.status >= 7 && info.checked_at) {
						this.currentProgress = 4;
						this.progressData[4].time = info.checked_at.split(" ")[0];
					}
					if (info.status >= 9 && info.end_at) {
						this.currentProgress = 5;
						this.progressData[5].time = info.end_at.split(" ")[0];
					}
				}
			},

			onTabChange(chunk) {
				this.currentIndex = chunk.index;
			},

			toFilesPage() {
				console.log("----->this.info.attachment", this.info.attachment)
				uni.setStorageSync("currentFiles", this.info.attachment);
				uni.navigateTo({
					url: `/pages/index/files`,
				});
			},

			// 原生APP分享
			onShare() {
				// #ifdef APP-PLUS
				let shareData = {
					shareUrl: `${this.$config.host}task/detail?id=${this.info.id}`,
					shareTitle: this.info.title,
					shareContent: this.info.time_desc,
					shareImg: "/static/images/logo_circle.png",
				};

				// 调用
				let shareObj = appShare(shareData, (res) => {
					console.log("分享成功回调", res);
					closeShare();
				});
				// #endif
			},
		},

		computed: {
			worker() {
				return this.info.work_list.filter((item) => item.status == 1)[0];
			},
			tabTitle() {
				let list = [
					"任务详情",
					`投标记录(${this.info.work_list.length})`,
					`修改记录(${this.updates.length})`,
				];

				if (this.deliverys.length != 0)
					list.push(`交付内容(${this.deliverys.length})`);

				return list;
			},
			buttonText() {
				if (this.info.role == "employee") {
					return this.info.employee_button_desc;
				} else if (this.info.role == "employer") {
					return this.info.employer_button_desc;
				} else {
					return "立即投标";
				}
			},
			buttonStatus() {
				if (this.info.role == "employee") {
					return this.info.employee_button;
				} else if (this.info.role == "employer") {
					return this.info.employer_button;
				} else {
					return 1;
				}
			},
			buttonDisabled() {
				if (this.info.role == "employee") {
					return [2, 3, 4, 5, 8, 9, 11, 12, 13, 14].includes(
						this.info.employee_button
					);
				} else if (this.info.role == "employer") {
					return [1, 2, 3, 6, 9, 10, 11, 12, 13].includes(
						this.info.employer_button
					);
				} else {
					return false;
				}
			},
			...mapState(["userInfo"]),
		},

		components: {
			uniTab,
			uniDialog,
			uniProgressBar,
			uniLoadMore,
			workItem,
			updateItem,
		},
	};
</script>

<style lang="scss" scoped>
	.router-view {
		padding-bottom: 100upx;

		.fixed-bottom-right {
			position: fixed;
			right: 20rpx;
			bottom: 200rpx;
			z-index: 10;

			&>view,
			&>button {
				padding: 20rpx;
			}
		}
	}
</style>
